﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using EfConsole.Entities;
using Microsoft.EntityFrameworkCore;

namespace EfConsole.Services
{
    public interface ITestService
    {
        void InitDatabase();

        Task<bool> AddProfileAsync(Profile profile);

        Task<Profile> GetProfileAsync(string id);

    }

    internal class TestService : ITestService
    {
        private readonly TestContext dbContext;
        private readonly IMapper mapper;

        public TestService(TestContext dbContext, IMapper mapper)
        {
            this.dbContext = dbContext;
            this.mapper = mapper;
        }

        public async Task<bool> AddProfileAsync(Profile profile)
        {
            var p = mapper.Map<Profile, ProfileEntity>(profile);
            await dbContext.Profiles.AddAsync(p);
            var result = await dbContext.SaveChangesAsync();
            return result > 0;
        }

        public async Task<Profile> GetProfileAsync(string id)
        {
            var entity = await dbContext.Profiles.FirstOrDefaultAsync(i => i.Id == id);
            if (entity != null)
            {
                return mapper.Map<ProfileEntity, Profile>(entity);
            }
            return null;
        }

        public void InitDatabase()
        {
            dbContext.Database.Migrate();
        }


    }
}
